<?php

namespace app\api\controller\v1;
include_once APP_PATH . 'api/common.php';

use app\admin\controller\auth\Group;
use app\common\controller\Api;
use think\Db;
use app\api\controller\v1\Event;
use think\Env;

class Classes extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function getList()
    {
        $list = Db::name("Classes")
            ->field("id, name")
            ->select();
        $this->success("获取成功", $list);
    }


    /**
     * 获取班级列表
     */
    public function getClassList()
    {
        $latitude = $this->request->get('latitude');
        $longitude = $this->request->get('longitude');
        $order = $this->request->get('order', 'price desc');

        $schoolId = $this->request->get('school_id');
        $page = $this->request->get('page', 1); // 获取当前页码，默认为1
        $pageSize = $this->request->get('pageSize', 10); // 获取每页条数，默认为10

        if (!$latitude || !$longitude) {
            $latitude = 22.81000000000000;
            $longitude = 108.35528564453125;
        }

        // 调用Event控制器的baseCourseQuery方法
        $eventController = new Event($this->request);
        $eventController->auth = $this->auth;

        $params = [
            'page' => $page,
            'limit' => $pageSize,
            'latitude' => $latitude,
            'longitude' => $longitude,
            'school_id' => $schoolId,
            'order' => $order
        ];

        $list = $eventController->baseCourseQuery($params);

        // 处理返回结果，保持与原来一致的输出格式
        foreach ($list as $key => $value) {
            $list[$key]['cover'] = preg_replace('/^https?\:\/\/.*\.myqcloud\.com\//', 'https://tcimg.gxyushengwenhua.com/', $value['cover']);
            $list[$key]['start_date'] = date('Y年m月d日', strtotime($value['start_date']));
            $list[$key]['date'] = date('Y年m月d日', strtotime($value['date']));
            $list[$key]['start_time'] = substr($value['start_time'], 0, 5);
            $list[$key]['km'] = $value['km'] !== null ? round($value['km'], 1) : 0;
            $list[$key]['address_lv_octionlevel'] = $list[$key]['address_lv_octionlevel'] == 2 ? "一级教学点" : "二级教学点";
            $list[$key]['tags'] = $value['tags'];
            if ($list[$key]['price'] == 0 && $list[$key]['classes_type'] != 2) {
                //$list[$key]['tags'][] = "免费";
            }
        }

        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => $list
        ]);
    }

    /**
     * 获取学校详情
     */
    public function getSchoolInfo()
    {
        //getcurl();
        // 支持多种方式接收学校ID参数
        $schoolId = $this->request->get('school_id'); 

        // 如果没有school_id，尝试从scene参数中解析
        if (!$schoolId) {

            $scene = $this->request->get('scene');
            if ($scene) {
                // scene参数格式: "123-45" (学校ID-随机数)
                $sceneParts = explode('-', $scene);
                $schoolId = $sceneParts[0] ?? null;
                \think\Log::write("从scene参数解析学校ID: scene=$scene, schoolId=$schoolId", 'debug');
            }
        }
        
        // 如果还是没有，尝试通用的id参数
        if (!$schoolId) {
            $schoolId = $this->request->get('id');
        }

        if (!$schoolId) {
            $schoolId = 1;
        }

        if (!$schoolId) {
            return json([
                'code' => 400,
                'msg' => print_r(json_encode($this->request->param()), true)
            ]);
        }
        
        \think\Log::write("最终使用的学校ID: $schoolId", 'debug');
        
        $schoolInfo = Db::name('eb_school')
            ->where('id', $schoolId)
            ->find();

        $list = $this->getClassList();
        $schoolInfo = [
            'name' => $schoolInfo['name'],
            'is_official' => $schoolInfo['is_official']?true:false,
            'logo' => getImg($schoolInfo['school_logo'], 144, 144),
            'image' => getImg($schoolInfo['thumbnail'], 750, 422),
            'description' => preg_replace('/https?\:\/\/.*\.myqcloud\.com\//Uisx', 'https://tcimg.gxyushengwenhua.com/', $schoolInfo['intro']),
            'address' => $schoolInfo['address'],
            'isCollected' => $this->isCollected($schoolId), // 这里可以根据用户是否收藏来判断，这里暂时设置为0
            'qrcode' => $schoolInfo['qrcode'],
            'list' => $list->getData()['data']
        ];

        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => $schoolInfo
        ]);
    }

    public function create()
    {
        $user = $this->auth->getUser();
        $data = $this->request->post();
        $classData = [
            'name' => $data['class_name'],
            'cover' => $data['class_cover'],
            'type' => $data['class_type'],
            'manager_id' => $data['class_admin'],
            'add_time' => time(),
            'create_time' => date("Y-m-d H:i:s"),
            'intro' => $data['class_description'],
            'is_apply_to_join' => $data['is_open_join'] === '是' ? 1 : 0,
            'is_check' => $data['is_verify_join'] === '是' ? 1 : 0,
            'show_in_team' => $data['is_show_in_team'] === '是' ? 1 : 0,
            'allow_see' => $data['is_member_can_view'] === '是' ? 1 : 0,
            'type' => $data['creator_type'] === '学校' ? 1 : 2, //1=学员|2=学校
            'creator_id' => isset($user['uid']) ? $user['uid'] : 0,
        ];

        Db::name('eb_classes')->insert($classData);
        $classId = Db::name('eb_classes')->getLastInsID();

        // 假设班级管理员也是班级学生之一
        Db::name('eb_class_student')->insert([
            'classes_id' => $classId,
            'student_id' => $data['class_admin'],
            'add_time' => time(),
        ]);

        $this->success('班级创建成功');
    }

    public function classTeamList()
    {
        $user = $this->auth->getUser();
        $list = Db::name("ClassStudent")
            ->alias("cs")
            ->join("Classes c", "cs.class_id = c.id")
            ->field("c.id, c.name")
            ->where("student_id", "=", $user['uid'])
            ->select();
        $this->success("获取成功", $list);
    }

    public function getClassInfo()
    {
        $classes_id = $this->request->get('classes_id');
        $t_id = $this->request->get('t_id');
        $table_type = $this->request->get('table_type');
        if ($table_type == null && $this->request->get('classes_type')) {
            $table_type = $this->request->get('classes_type');
        }
        $user = $this->auth->getUser(true);

        if (!$classes_id) {
            $this->error('班级ID不能为空');
        }

        if ($table_type == 1 || $table_type == null) {
            $classInfo = Db::name("eb_classes")->where('id', $classes_id)->find();
            if (!empty($classInfo)) {
                $table_type = 1;
            } else {
                $classInfo = Db::name("fa_ocation_class")->where('id', $classes_id)->find();
                $table_type = 2;
            }

        } elseif ($table_type == 2) {
            $classInfo = Db::name("fa_ocation_class")->where('id', $classes_id)->find();
            $table_type = 2;
        }
        $Apply = 0;
        if (isset($user['uid'])) {
            $Apply = Db::name('eb_apply_form_item')->where(['classes_id' => $classes_id, 'user_id' => $user['uid'], 'classes_type' => $table_type,'status'=>1])->find();
        }
        $row=array();
        if($table_type==""||$table_type=="undefined"){
            $table_type=1;
        }

        $alreadyApply = ($Apply) ? 1 : 0;
        if ($table_type == 1) {
            $query = "SELECT
            plt.id AS t_id,
            c.id AS class_id,
            c.name AS class_name,
            s.name AS school_name,
            s.id AS school_id,
            sl.name AS subject_name,
            sl.name AS course_name,
            c.subject_lv AS subjectlv_id,
            c.classes_type,
            c.intro AS course_content,
            c.apply_num AS enrolled_students,
            c.num AS total_capacity,
            c.num AS num,
            c.apply_num,
            c.player_num,
            COALESCE(ct.start_date, CONCAT(plt.date, ' ', plt.start_time)) AS start_time,
            COALESCE(ct.end_date, CONCAT(plt.date, ' ', plt.end_time)) AS end_time,
            COALESCE(o.name, o2.name, '未设置地点') AS location,
            o2.name AS location_detail,
            o2.id AS location_id,
            c.ocation_id,
            c.community_id,
            c.parent_teaching_ocation_id,c.image as image_course,
            o2.name AS parent_teaching_ocation_name,
            o3.id AS top_teaching_ocation_id,
            o3.name AS top_teaching_ocation_name,
            plt.area_teaching_ocation_id,
            c.is_free,c.header_image as header_image_classes,o2.header_image as header_image_ocation,s.thumbnail as header_image_school,c.header_image as header_image_course,
            COALESCE(o.address, o2.address, '') AS address,
            COALESCE(t.name, teacher.name, '待安排') AS teacher_name,
            c.price AS tuition_fee,
            c.cover,
            COALESCE(o.latitude, o2.latitude) as latitude,
            COALESCE(o.longitude, o2.longitude) as longitude,
            o2.address_lv_octionlevel,
            c.rel_type,
            plt.subjectlv_id_b,
            f.id as apply_from_id,
            afitem.form_id as apply_id,
            0 as publicwelfare_id,
            '' as publicwelfare_name,
            c.image,
            cplant.ocourse_count course_count,
            COALESCE(o.header_image, c.header_image) as header_image,
            tb.start_date table_start_date,c.table_id,
            (NOW() > (SELECT MIN(CONCAT(t2.date,' ', t2.start_time, ':00')) FROM fa_course_table_autoplan t2 WHERE t2.status=1 AND t2.classes_id=c.id AND t2.table_type=plt.table_type)) as is_started ,f.id as apply_id,f.status>0 as is_applyed,ord.payment_status,ord.amount as order_amount,ord.id as order_id,ord.pay_status,ord.pay_status<1 as is_wait_pay,
            1 as course_type
        FROM  
             eb_classes c
        left join 
             fa_course_table_autoplan plt on c.id = plt.classes_id
        LEFT JOIN 
            eb_school s ON c.school_id = s.id 
        LEFT JOIN 
            fa_subject_lv sl ON c.subject_lv = sl.id
        LEFT JOIN 
            eb_course ct ON c.id = ct.class_id
        LEFT JOIN 
            fa_ocation o ON o.id=plt.ocation_id
        LEFT JOIN 
            fa_ocation o2 ON o.pid = o2.id
        LEFT JOIN 
            fa_ocation o3 ON o3.id=o2.pid
        LEFT JOIN 
            eb_class_teacher t ON ct.teacher_id = t.id
        LEFT JOIN 
            eb_class_teacher teacher ON c.id = teacher.classes_id
        LEFT JOIN 
            eb_apply_form_item afitem ON afitem.classes_id = c.id AND afitem.user_id = :user_id AND afitem.classes_type = :classes_type and afitem.status=1
        LEFT JOIN 
            eb_apply_form f ON f.id=afitem.form_id
        LEFT JOIN 
            fa_order ord ON ord.id = afitem.order_id
        LEFT JOIN
            fa_course_table tb ON tb.id = plt.table_id
        LEFT JOIN
            fa_course_table_classplant cplant ON cplant.table_id = tb.id and cplant.classes_id = c.id
        WHERE 
            c.id = :classes_id
            AND c.delete_time IS NULL";
            $query .= " GROUP BY c.id";
            $result = Db::query($query, ['classes_id' => $classes_id, 'user_id' => isset($user['uid']) ? $user['uid'] : 0, 'classes_type' => $table_type]);//
            $query = Db::getLastSql();
            if (empty($result)) {
                return $this->error('班级信息不存在');
            }
            // 安全地获取申请人数统计，防止SQL注入和空值异常
            if (empty($result[0]['class_id'])) {
                $result[0]['apply_num'] = 0;
            } else {
                try {
                    $apply_items = Db::query("SELECT count(*) as apply_num FROM `eb_apply_form_item` WHERE pay_status=1 AND STATUS=1 AND classes_id=:classes_id", ['classes_id' => $result[0]['class_id']]);
                    $result[0]['apply_num'] = !empty($apply_items[0]['apply_num']) ? (int)$apply_items[0]['apply_num'] : 0;
                } catch (\Exception $e) {
                    // 记录错误日志但继续执行
                    $result[0]['apply_num'] = 0;
                }
            }
            $row = $result[0];
            try {
                // 安全更新班级申请人数
                db::name("eb_classes")->where("id", $classes_id)->update(['apply_num' => $result[0]['apply_num']]);
            } catch (\Exception $e) {
                // 记录错误日志但继续执行，不影响主要功能
            }
            
            // 确保course_content字段不为null，避免format_content方法中的preg_replace警告
            if (!isset($row['course_content']) || $row['course_content'] === null) {
                $row['course_content'] = '';
            }
        } else if ($table_type == 2) {
            $query = "SELECT 
             t.id as t_id,t.classes_id AS class_id,t.subject_lv,c.name as subject_name,'2' as rel_type,t.school_id,s.name school_name,t.subjectlv_id_b,
             CONCAT(t.date, ' ', t.start_time) AS start_time,
             CONCAT(t.date, ' ', t.end_time) AS end_time,
             '0' AS tuition_fee,'0' as price,99 as num,
             classes.apply_num,
            classes.player_num,
            s.name AS school_name,publicwelfare.project_name AS publicwelfare_name,
            o.address_lv_octionlevel,2 rel_type,c.cover, 
            c.intro AS course_content,
            COALESCE(o.address, o2.address, '') AS address, 
            COALESCE(o.name, o2.name, '未设置地点') AS location,
            classes.classes_type,
            classes.ocation_id,
            classes.community_id,
            classes.parent_teaching_ocation_id,
            o2.name AS parent_teaching_ocation_name,
            o.id AS location_id,
            o3.id AS top_teaching_ocation_id,
            o3.name AS top_teaching_ocation_name,
            t.area_teaching_ocation_id,
            classes.is_free,classes.ocation_id as oation_id_classes,
            o.name AS location_detail,
            c.name as course_name,
            c.name AS class_name,
            COALESCE(o.longitude, o2.longitude) as longitude,
            COALESCE(o.latitude, o2.latitude) as latitude,
            f.id as apply_from_id,f.id as apply_id,f.id>0 as is_applyed,ord.payment_status,ord.amount as order_amount,f.id>0 && ord.payment_status = 0 && ord.amount > 0 as is_wait_pay,t.publicwelfare_id,'' AS intro,
            COALESCE(teacher.name, '待安排') AS teacher_name,
            classes.image,o.image AS image_ocation,s.image as image_school,
            classes.header_image,o.header_image as header_image_ocation,s.thumbnail as header_image_school,c.image as image_course,
            1 as course_count,
            2 as course_type
            from fa_course_table_autoplan t
            left join fa_community_course_config c ON c.id =t.subject_lv
            left join fa_community_code_config comc ON comc.id = t.ocation_id
            LEFT JOIN fa_ocation o ON o.id = t.ocation_id
            LEFT JOIN fa_ocation o2 ON o.pid=o2.id
            LEFT JOIN fa_ocation o3 ON o3.id=o2.pid
            LEFT JOIN eb_school s ON s.id = t.school_id
            LEFT JOIN fa_ocation_class classes ON classes.id = t.classes_id 
            LEFT JOIN fa_community_publicwelfare publicwelfare ON publicwelfare.id = t.publicwelfare_id
            LEFT JOIN eb_class_teacher teacher ON classes.id = teacher.classes_id   
            LEFT JOIN 
                eb_apply_form_item afitem ON afitem.classes_id = c.id AND afitem.user_id = :user_id AND afitem.classes_type = :classes_type
            LEFT JOIN fa_order ord ON ord.id = afitem.order_id
            LEFT JOIN 
                eb_apply_form f ON f.id=afitem.form_id 
            where t.id = '{$t_id}'";
            $result = Db::query($query, ['user_id' => (array_key_exists('uid', $user) ? $user['uid'] : 0), 'classes_type' => $table_type]);
            //输出sql
            $query = Db::getLastSql();
            if (empty($result)) {
                return $this->error('班级信息不存在');
            }
            $row = $result[0];
        }

        // 修复address_lv_octionlevel字段未定义的错误
        if (!isset($row['address_lv_octionlevel'])) {
            $row['address_lv_octionlevel'] = "4"; // 默认设置为4级教学点
        }

        if ($row['address_lv_octionlevel'] == "1") {
            $row['address_lv_octionlevel'] = "一级教学点";
        } else if ($row['address_lv_octionlevel'] == "2") {
            $row['address_lv_octionlevel'] = "二级教学点";
        } else if ($row['address_lv_octionlevel'] == "3") {
            $row['address_lv_octionlevel'] = "三级教学点";
        } else {
            $row['address_lv_octionlevel'] = "二级教学点";
        }

        // 设置默认图片
        $defaultImageUrl = "https://dev002.gxyushengwenhua.com/uploads/20241223/1c2e43fffe96d0dc0374cd5b9307868a_750_422.png?";
        $defaultImages = array(
            array("url" => "https://static.gxrb.com.cn/image/uploadpic/20250716/90b949e2bfbba07a84030a9d6f21937e.jpeg", "title" => "inant Museum“上新”！左江花山岩画展惊艳升级", "href" => "http://www.gxnews.com.cn/staticpages/20250716/newgx687700ad-21821764.shtml"),
            array("url" => "https://static.gxrb.com.cn/image/uploadpic/20241115/14a0c2a3f17142d570c903e4a8cdaaf8_wm3bed.jpg", "title" => "今起生效！中国“免签朋友圈”再+1", "href" => "http://www.gxnews.com.cn/staticpages/20250716/newgx687712cd-21821832.shtml"),
            array("url" => "https://static.gxrb.com.cn/image/uploadpic/20250715/8ac389958e1d18262cb7fb4373159906_wme911.jpg", "title" => "红润清甜“象州味”！200多亩晚熟禾荔迎丰收，生态山间结出致富果", "href" => "http://www.gxnews.com.cn/staticpages/20250716/newgx6876ede7-21821782.shtml"),
        );

        // 如果cover为空，则设置默认值
        if (empty($row['cover'])) {
            $row['cover'] = getImg($defaultImageUrl, 114, 114);
        } else {
            $row['cover'] = getImg($row['cover'], 114, 114);
        }
        if($row['image_course']!=null) {
            $image_course = json_decode($row['image_course'], 1);
        }
        if(isset($image_course)&&$row['image_course']!="[]"&&is_array($image_course) && !empty($image_course)&&$image_course!="[]"){
            $row['image_course']= getImg($image_course[0]['url'], 750, 422);
        }
        if (empty($row['image_course'])&&!empty($row['header_image'])) {
            $row['image_course']= getImg($row['header_image'], 750, 422);
        }
        if (empty($row['image_course'])&&!empty($row['header_image_ocation'])) {
            $row['image_course']= getImg($row['header_image_ocation'], 750, 422);
        }
        if (empty($row['image_course'])&&!empty($row['header_image_school'])) {
            $row['image_course']= getImg($row['header_image_school'], 750, 422);
        }

        $row['image_course']= getImg($row['header_image_course'], 750, 422);

        if (empty($row['apply_num'])) {
            $row['apply_num'] = 0;
        }
        // 如果image为空，则设置默认值
        if (empty($row['image'])) {
            $row['image'] = $defaultImages;
        } else {
            $row['image'] = json_decode($row['image'], true);
            if (is_string($row['image'])) {
                $row['image'] = json_decode($row['image'], true);
            }
        }
        if($row['location_detail']==""){
            $row['location_detail']=$row['location'];
        }
        $row['location_detail'] = !empty($row['location_detail']) ? preg_replace("/教学点$/U", "", $row['location_detail'])."教学点" : "";

        // 如果header_image为空，则设置默认值
        if (empty($row['header_image'])) {
            if(!empty($row['header_image_ocation'])){
                $row['header_image'] = getImg($row['header_image_ocation'], 750, 422);
            }elseif(!empty($row['header_image_school'])){
                $row['header_image'] = getImg($row['header_image_school'], 750, 422);
            }else{
                $row['header_image'] = getImg("/uploads/20241223/1c2e43fffe96d0dc0374cd5b9307868a.png", 750, 422);
            }
        } else {
            $row['header_image'] = getImg($row['header_image'], 750, 422);
        }
        if (empty($row['header_image_ocation'])) {
            $row['header_image_ocation'] = getImg("/uploads/20241223/1c2e43fffe96d0dc0374cd5b9307868a.png", 750, 422);
        } else {
            $row['header_image_ocation'] = getImg($row['header_image_ocation'], 750, 422);
        }

        if (is_array($row['image']) && !empty($row['image'])) {
            foreach ($row['image'] as $k => $v) {
                if (is_string($v) && strlen($v) > 0 && substr($v, 0, 1) == "/") {
                    $row['image'][$k]['url'] = Env::get('img.baseurl') . $v;
                }
            }
        }



        // 获取课程名称
        $courseName = $row['course_name'];

        // 构造班级名称：社区名+课程名+公益项目名
        $className = $courseName . ($publicwelfareInfo['project_name'] ?? '');

        if ($row['rel_type'] == "2") {
            $tags[] = "社区";
            $tags[] = "免费";
            $communityName = "【" . $row['location'] . "】";
            $row['classes_name'] = $row['location'] . "班";
        } else if ($row['rel_type'] == "1") {
            $tags[] = "积分兑换 ";
            $communityName = "";
            $row['classes_name'] = $row["class_name"];
            $row["class_name"] = !empty($className) ? preg_replace("/课程?$/", "", $className) . "课" : "";
        }

        $row['tags'] = array_unique($tags);
        $row['alreadyApply'] = $alreadyApply;
        $row['apply_id'] = $Apply['id'] ?? null;
        $row['is_started'] = 1;

        $row['communityName'] = $communityName;
        if (!$row) {
            $this->error('未找到相关班级信息');
        }
        //是否已经报名

        // 确保必要字段不为空，设置默认值
        if (empty($row['location'])) {
            $row['location'] = '未设置地点';
        }
        if (empty($row['teacher_name'])) {
            $row['teacher_name'] = '待安排';
        }
        // 确保location_id字段不为空，使用ocation_id作为备用
        if (empty($row['location_id'])) {
            $row['location_id'] = $row['ocation_id'] ?? '';
        }
        if (empty($row['start_time'])) {
            // 尝试从课程表获取时间信息
            $r = Db::name('fa_course_table_autoplan_temp')->where('classes_id', $classes_id)->order("date")->limit(0, 1)->find();
            if ($r) {
                $row['start_time'] = $r['date'] . ' ' . ($r['start_time'] ?? '09:00');
            } else {
                $row['start_time'] = '';
            }
        }
        if (empty($row['end_time'])) {
            $r2 = Db::name('fa_course_table_autoplan_temp')->where('classes_id', $classes_id)->order("date desc")->limit(0, 1)->find();
            if ($r2) {
                $row['end_time'] = $r2['date'] . ' ' . ($r2['end_time'] ?? '17:00');
            } else {
                $row['end_time'] = '';
            }
        }

        // 确保返回的数据不为null
        if (!$row || empty($row)) {
            $this->error('班级信息不存在或数据异常');
        }

        // 添加apply_form_id字段，优先使用apply_from_id，其次使用apply_id
        // 注意：0也是一个有效的值，所以不能使用??运算符
        if (isset($row['apply_from_id']) && $row['apply_from_id'] !== null) {
            $row['apply_form_id'] = $row['apply_from_id'];
        } elseif (isset($row['apply_id']) && $row['apply_id'] !== null) {
            $row['apply_form_id'] = $row['apply_id'];
        } else {
            // 如果都没有设置，尝试从eb_apply_form表获取一个默认的申请表单ID
            $defaultForm = Db::name('eb_apply_form')->where('status', 1)->order('id asc')->find();
            $row['apply_form_id'] = $defaultForm ? $defaultForm['id'] : 1; // 默认使用ID为1的申请表单
        }

        // 确保course_content字段不为null，避免format_content方法中的preg_replace警告
        if (!isset($row['course_content']) || $row['course_content'] === null) {
            $row['course_content'] = '';
        }
        $row['course_content'] = $this->format_content($row['course_content']);


        $result=Db::table('eb_apply_form')->alias('f')
            ->join("fa_course_table table", "f.table_id=table.id", "left")
            ->where('table_id',  $row['table_id'])
            ->where('f.status', 1)
            ->where('is_close', 0)
            ->where('is_finished', 0)
            ->where('is_user_end', 0)
            ->where('is_end', 0)
            //->where('dead_time', '>', date('Y-m-d H:i:s'))
            ->field('f.id,table.name table_name,table_id,apply_type,title,intro,cover,terms_content,`male_age_min`,`male_age_max`,`female_age_min`,`female_age_max`,f.start_time,f.end_time,max_num,is_use_integral,dead_time,f.applyed_count')
            ->select();
        if($result&&$result[0]['male_age_min']!==null){
            $row['male_age_min']=$result[0]['male_age_min'];
        }
        if($result&&$result[0]['male_age_max']){
            $row['male_age_max']=$result[0]['male_age_max'];
        }
        if($result&&$result[0]['female_age_min']){
            $row['female_age_min']=$result[0]['female_age_min'];
        }
        if($result&&$result[0]['female_age_max']){
            $row['female_age_max']=$result[0]['female_age_max'];
        }
        if($result&&$result[0]['terms_content']!==null){
            $row['terms_content']=$this->format_content($result[0]['terms_content']);
            $row['terms_content']=preg_replace('/<([^\s]+)\s[^<>]*>/isx', '<\\1>', $row['terms_content']);
        }

        $this->success('获取成功', $row);
    }

    function format_content($content)
    {
        // 确保参数不为null，如果是null则转换为空字符串
        if ($content === null || $content === '') {
            return '';
        }

        // 处理HTML内容，为h1标签添加内联样式
        $processedContent = (string)$content;

        // 使用正则表达式匹配从段落头部开始到h1标签的部分
        $processedContent = preg_replace(
            '/^([^>])+<h1([^>]*)>/im',
            '<h1$2 style="font-size: 22px; color: #333; font-weight: bold; text-align: center; margin-left: -50px;margin-top: 20px;margin-bottom: 20px; line-height: 1.5;">',
            $processedContent
        );

        // 确保preg_replace返回的是字符串，而不是null
        if ($processedContent === null) {
            $processedContent = (string)$content;
        }

        // 为h2标签添加样式
        $processedContent = preg_replace(
            '/<h2([^>]*)>/i',
            '<h2$1 style="font-size: 18px; color: #000; font-weight: bold; margin: 15px 0 10px; line-height: 2.5;">',
            $processedContent
        );

        // 确保preg_replace返回的是字符串，而不是null
        if ($processedContent === null) {
            $processedContent = (string)$content;
        }

        // 为p标签添加样式
        $processedContent = preg_replace(
            '/<p([^>]*)>/i',
            "
            <p$1 style=\"font-size: 16px; color: #000; line-height: 1.6; margin: 10px 0; text-indent: 2em; line-height: 1.5;\">",
            $processedContent
        );
        $processedContent = preg_replace(
            '/^/i',
            "
            <p>",
            $processedContent
        );
        // 确保preg_replace返回的是字符串，而不是null
        if ($processedContent === null) {
            $processedContent = (string)$content;
        }

        return $processedContent;
    }

    function getClassesIsApplyed()
    {
        $user = $this->auth->getUser();
        if (!$user) {
            $this->error('未登录', [], '402');
        }
        $classes_id = $this->request->get('classes_id');
        $Apply = Db::name('eb_apply_form_item')->where(['classes_id' => $classes_id, 'user_id' => isset($user['uid']) ? $user['uid'] : 0])->find();
        $alreadyApply = ($Apply) ? true : false;
        $msg = ($Apply) ? "已报名" : "未报名";
        $this->success($msg, array("ClassesIsApplyed" => $alreadyApply, "apply_id" => $Apply['id'] ?? null), 200);
    }

    public function isCollected($school_id, $collect_type = 0)
    {
        $user = $this->auth->getUser(true);
        if (!$user) {
            return false;
        }
        $user_id = isset($user['uid']) ? $user['uid'] : 0;
        try {
            $result = Db::name('favorites')->where(['user_id' => $user_id, 'type' => $collect_type, 'target_id' => $school_id, 'delete_time' => null])->find();
            if ($result) {
                return true;
            } else {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }

    protected function getCourseData($publicwelfare_id = 0)
    {
        // 从数据库直接获取课程数据，确保使用整数ID
        $courses = Db::name('fa_community_course_config')
            ->where('status', 1)
            ->where('delete_time', null)
            ->field('code, name')
            ->select();

        $list = [];
        foreach ($courses as $course) {
            $list[$course['code']] = $course['name'];
        }

        // 如果没有数据，返回默认列表
        if (empty($list)) {
            return [
                1 => '音乐',
                2 => '舞蹈',
                3 => '书法',
                4 => '绘画',
                5 => '钢琴',
                6 => '太极',
                7 => '剪纸',
                8 => '中医',
                9 => '国画',
                10 => '生活',
                11 => '运动',
                12 => '主持'
            ];
        }

        return $list;
    }

    /**
     * 获取社区数据，使用整数ID作为键值
     */
    protected function getCommunityData($publicwelfare_id = 0)
    {
        // 从数据库直接获取社区数据，确保使用整数ID
        $communities = Db::name('fa_community_code_config')
            ->where('status', 1)
            ->field('code, name')
            ->select();

        $list = [];
        foreach ($communities as $community) {
            $list[$community['code']] = $community['name'];
        }

        // 如果没有数据，返回默认列表
        if (empty($list)) {
            $list = [];
            for ($i = 1; $i <= 5; $i++) {
                $list[$i] = chr(64 + $i) . '社区'; // A-E社区
            }
        }

        return $list;
    }

    /**
     * 获取时区数据，使用整数ID作为键值
     */
    protected function getTimeZoneData($publicwelfare_id = 0)
    {
        // 从数据库直接获取时区数据，确保使用整数ID
        $timezones = Db::name('community_timezone_config')
            ->where('status', 1)
            ->where('delete_time', null)
            ->field('code, name')
            ->select();

        $list = [];
        foreach ($timezones as $timezone) {
            $list[$timezone['code']] = $timezone['name'];
        }

        // 如果没有数据，返回默认列表
        if (empty($list)) {
            return [
                1 => '上午',
                2 => '下午',
                3 => '晚上'
            ];
        }

        return $list;
    }

    /**
     * 获取时间段的详细信息，包括天数
     */
    protected function getTimeSlotDetails($publicwelfare_id = 0)
    {
        // 从数据库直接获取时间段数据
        $result = Db::name('fa_community_timeslot_config')
            ->where('status', 1)
            ->where('delete_time', null)
            ->field('id, code, name, day, start_time, end_time')
            ->select();
        $this->timeSlotDetails = $result;

        // 获取时区数据，用于获取年份和月份
        $timeZoneData = Db::name('fa_community_timezone_config')
            ->field('id, code, name')
            ->select();

        $timeZones = [];
        foreach ($timeZoneData as $zone) {
            preg_match('/(\d+)年(\d+)月/', $zone['name'], $matches);
            $timeZones[$zone['code']] = [
                'year' => $matches[1] ?? date('Y'), // 如果没有年份，使用当前年份
                'month' => $matches[2] // 如果没有month，使用code作为月份
            ];
        }

        $list = [];
        $currentMonth = date('n');
        $currentYear = date('Y');

        // 生成时间段列表，并为每个时间段生成对应的时区数据
        foreach ($result as $key => $value) {
            $days = explode(',', $value['day']);
            foreach ($days as $k => $day) {
                // 为每个时区生成一个时间段条目
                foreach ($timeZones as $timeZoneCode => $timeZoneInfo) {
                    $list[] = array(
                        'id' => $value['code'],
                        'day' => intval($day),
                        'month' => $timeZoneInfo['month'],
                        'year' => $timeZoneInfo['year'],
                        'time_zone_code' => $timeZoneCode,
                        'startTime' => $value['start_time'],
                        'endTime' => $value['end_time'],
                        'text' => $day . "号 " . $value['start_time'] . "-" . $value['end_time'],
                        'originalText' => $value['start_time'] . "-" . $value['end_time'],
                    );
                }
            }
        }
        return $list;
    }

    /**
     * 获取时间段数据，使用整数ID作为键值
     */
    protected function getTimeSlotData($publicwelfare_id = 0)
    {
        // 从数据库直接获取时间段数据，确保使用整数ID
        $timeslots = Db::name('community_timeslot_config')
            ->where('status', 1)
            ->where('delete_time', null)
            ->field('id, code,name, day, start_time, end_time')
            ->select();

        $list = [];
        foreach ($timeslots as $timeslot) {
            // 如果 name 字段已经包含完整的显示名称，直接使用
            if (!empty($timeslot['name'])) {
                $list[$timeslot['code']] = $timeslot['name'];
            } else {
                // 否则组合日期和时间
                $startTime = date('H:i', strtotime($timeslot['start_time']));
                $endTime = date('H:i', strtotime($timeslot['end_time']));
                $list[$timeslot['code']] = $timeslot['day'] . '号 ' . $startTime . '-' . $endTime;
            }
        }

        // 如果没有数据，返回默认列表
        if (empty($list)) {
            $days = [20, 25, 30];
            $times = [
                '上午8:30-9:10',
                '上午9:20-10:10',
                '下午15:00-15:50'
            ];

            $list = [];
            $index = 1;
            foreach ($days as $day) {
                foreach ($times as $time) {
                    $list[$index] = $day . '号' . $time;
                    $index++;
                }
            }
        }

        return $list;
    }

    public function applyJoinClass()
    {
        $classes = [[$this->request->get("classes_id"), $this->request->get("classes_type")]];
        $user = $this->auth->getUser();
        $result = model("app\admin\model\Apply")->baoming($classes, $user);
        if (is_array($result) && $result['code'] != 200) {
            $this->error($result['msg'], $result['data'], $result['code']);
        }
        return $result;
    }
}
